<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\UserAdvice;

class AdviceService
{
    public static function add($data)
    {
        $insertData['content'] = $data['content'];
        $insertData['user_id'] = get_user_id();
        $insertData['thumbs'] = json_encode($data['thumbs'], JSON_UNESCAPED_UNICODE);
        $insertData['created_time'] = date('Y-m-d H:i:s');
        UserAdvice::insert($insertData);
    }

    public static function list($page, $length = 10)
    {
        $offset = ($page - 1) * $length;
        $query = UserAdvice::where('user_id', get_user_id());

        $totalCount = (clone $query)->count();
        $list = $query->orderByDesc('id')->offset($offset)->limit($length)->get()->toArray();

        foreach ($list as $key=>$item) {
            $item['thumbs'] = json_decode($item['thumbs'], true);
            $list[$key] = $item;
        }

        return Page::wrap($totalCount, $page, $length, $list);
    }

    public static function detail($id)
    {
        $advice = UserAdvice::find($id);
        $advice['thumbs'] = json_decode($advice['thumbs'], true);

        return $advice;
    }
}